import moment from 'moment';

export const toFixed = (number, n) => {
    /**
     * @ params number 1.2345678
     * @ params n 0 | 1 | 2 | ···
     */
    var f = Math.round(number * Math.pow(10, n)) / Math.pow(10, n);
    var s = f.toString();
    var rs = s.indexOf('.');
    if (rs < 0) {
        s += '.';
    }
    for (var i = s.length - s.indexOf('.'); i <= n; i++) {
        s += '0';
    }
    return s;
};

export const isUrl = url => {
    const urlStr = url;
    // 判断URL地址的正则表达式为:http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?
    // 下面的代码中应用了转义字符"\"输出一个字符"/"
    // eslint-disable-next-line
    const Expression = /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/;
    const objExp = new RegExp(Expression);
    if (objExp.test(urlStr)) {
        return true;
    } else {
        return false;
    }
};

let removeSpinTimer = null;
export const removeSpin = (pathname, query, dispatch) => {
    clearTimeout(removeSpinTimer);
    if (pathname === '/') {
        return null;
    }
    try {
        const dom = window.document.querySelectorAll('#app-spin')[0];
        if (!dom) {
            return null;
        }
        dom.style.transition = 'all .6s';
        dom.style.opacity = 0;
        dom.style.zIndex = -1;
        removeSpinTimer = window.setTimeout(() => {
            dom.remove();
        }, 600);
    } catch (error) {}
    return null;
};

export const setTimeSection = (datetime, num, type = 'days') => {
    /**
     * 设置时间区间
     */
    let newDateTime = [];
    if (!Array.isArray(datetime)) {
        throw new Error('datetime Not a Array');
    }
    if (!datetime.length && num) {
        // 设置
        newDateTime = [moment().subtract(num, type), moment()];
    }
    if (datetime.length) {
        // 解析
        newDateTime = [moment(datetime[0]), moment(datetime[1])];
    }
    return newDateTime;
};
